package com.ja.openchat.ui.chat;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;

import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityFileDisplayBinding;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.viewmodels.FileDisplayViewModel;
import com.ja.openchat.views.AppFileReaderView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;
import com.zy.openchat.App;
import com.zy.openchat.util.share.GoShare;

import java.io.File;

public class FileDisplayActivity extends JaBaseActivity<ActivityFileDisplayBinding, FileDisplayViewModel> implements AppFileReaderView.OnTBSOpenCallback {

    public static final String BUNDLE_FILE_URL = "bundle_file_url";
    public static final String BUNDLE_FILE_TITLE = "bundle_file_title";
    public static final String BUNDLE_FILE_EXTENSION = "bundle_file_extension";


    public static void startActivity(Context context, String fileUrl,String fileExtension){
        String fileType = TextUtils.isEmpty(fileExtension)?AppFileReaderView.getFileType(fileUrl):fileExtension;
        if(TextUtils.isEmpty(fileType)||QbSdk.isSuportOpenFile(fileType,1)||!QbSdk.isSuportOpenFile(fileType,2)){
            startInnerActivity(context,fileUrl,fileExtension);
        }else if(!TextUtils.isEmpty(fileType)&&QbSdk.checkApkExist(context,"com.tencent.mtt")&&QbSdk.isSuportOpenFile(fileType,2)){
            QbSdk.openFileReader(context, fileUrl, null, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    if ("openFileReader open in QB".equals(s)
                            || "filepath error".equals(s)
                            || "TbsReaderDialogClosed".equals(s)
                            || "fileReaderClosed".equals(s)) {
                        QbSdk.closeFileReader(context);
                    }
                }
            });
        }else{
            startInnerActivity(context,fileUrl,fileExtension);
        }
    }

    public static void startInnerActivity(Context context, String fileUrl,String fileExtension){
        Intent intent = new Intent(context, FileDisplayActivity.class);
        intent.putExtra(BUNDLE_FILE_URL,fileUrl);
        intent.putExtra(BUNDLE_FILE_EXTENSION,fileExtension);
        context.startActivity(intent);
    }


    private AppFileReaderView mDocumentReaderView;
    private View unSupportHint;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_file_display;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public FileDisplayViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(FileDisplayViewModel.class);
    }

    private String fileExtension;
    @Override
    public void initView() {
        super.initView();
        fileExtension = getIntent().getStringExtra(BUNDLE_FILE_EXTENSION);
        mDocumentReaderView = findViewById(R.id.documentReaderView);
        mDocumentReaderView.setCallback(this);
        unSupportHint = findViewById(R.id.unSupportHint);
        ImageView barRight = findViewById(R.id.iv_bar_right);
        barRight.setImageResource(R.mipmap.nav_point_more);
        barRight.setVisibility(View.VISIBLE);
        barRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMore(FileDisplayActivity.this,fileUrl,fileExtension);
            }
        });
        if(getIntent() != null){
            if(!TextUtils.isEmpty(getIntent().getStringExtra(BUNDLE_FILE_TITLE))){
                setTitle(getIntent().getStringExtra(BUNDLE_FILE_TITLE));
            }else{
                setTitle(getString(R.string.file_preview));
            }
            if(!TextUtils.isEmpty(getIntent().getStringExtra(BUNDLE_FILE_URL))){
                fileUrl = getIntent().getStringExtra(BUNDLE_FILE_URL);
                openFile(fileUrl);
            }
        }
    }

    @Override
    public void onSuccess() {
        unSupportHint.setVisibility(View.GONE);
    }

    @Override
    public void onError() {
        unSupportHint.setVisibility(View.VISIBLE);
    }

    public static void showMore(FragmentActivity context, String fileUrl,String fileExtension){
        new XPopup.Builder(context).asBottomList(null, new String[]{context.getString(R.string.share_text),context.getString(R.string.other_to_open)}, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                if(TextUtils.isEmpty(fileUrl)){
                    return;
                }
                if(position==0){
                    new GoShare.FShareBuilder(context, App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                            .setFilePath(fileUrl)
                            .setShareSubject(context.getResources().getString(R.string.app_name))
                            .build()
                            .shareByCustom();
                }else{
                    openAndroidFile(context,fileUrl,fileExtension);
                }
            }
        }).show();
    }

    private String fileUrl;


    public static void openAndroidFile(Context context,String filepath,String fileExtension){
        Intent intent = new Intent();
        File file = new File(filepath);
        intent.setAction(Intent.ACTION_VIEW);//动作，查看
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".utilcode.fileprovider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }

        intent.setDataAndType(uri,getMIMEType(file.getAbsolutePath(),fileExtension));//设置类型
        context.startActivity(intent);
    }

    public static String getMIMEType(String filePath,String fileExtension) {
        String fileType = TextUtils.isEmpty(fileExtension)?AppFileReaderView.getFileType(filePath):fileExtension;
        if(TextUtils.isEmpty(fileType)){
            return "*/*";
        }else{
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileType);
        }

    }

    private void openFile(String fileurl) {
        mDocumentReaderView.show(fileurl);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDocumentReaderView != null) {
            mDocumentReaderView.stop();
        }
    }



}
